package club.itstudio.IContainer.annotation;

import club.itstudio.IContainer.exception.BaseException;
import club.itstudio.IContainer.service.RecaptchaService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class RecaptchaRequiredHandler {

    private RecaptchaService recaptchaService;

    @Autowired
    public void setRecaptchaService(RecaptchaService recaptchaService) {
        this.recaptchaService = recaptchaService;
    }

    @Around("@annotation(club.itstudio.IContainer.annotation.RecaptchaRequired)")
    public Object recaptchaRequired(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) throw new BaseException("系统错误");

        HttpServletRequest request = attributes.getRequest();
        String token = request.getParameter("token");
        if (!recaptchaService.valid(token)) {
            throw new BaseException("人机验证失败，请刷新页面后重试");
        }

        return joinPoint.proceed();
    }
}
